<template>
  <div>
    <van-cell
      :title="item"
      icon="search"
      v-for="(item, index) in suggestions"
      :key="index"
      @click="clickSuggestion(item)"
    >
      <template #title>
        <span v-html="formatStr(item)"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  watch: {
    // 监听搜索关键词
    value: {
      // handler (nval) {
      //   clearTimeout(this.setId)
      //   this.setId = setTimeout(() => {
      //     console.log(nval)
      //   }, 900)
      //  lodash的防抖函数
      handler: debounce(function (nval) {
        if (!this.isShow) return
        this.loadSearchSuggestion(nval)
      }, 900),
      // 该回调将会在侦听开始之后被立即调用
      immediate: true
    }

  },
  data () {
    return {
      // 防抖定时器
      // setId: null,
      // 联想建议列表
      suggestions: [],
      //
      isShow: true
    }
  },
  created () {

  },
  methods: {
    // 获取联想建议列表
    async loadSearchSuggestion (nval) {
      try {
        const res = await getSearchSuggestion(nval)
        this.suggestions = res.data.data.options
        console.log(this.suggestions)
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    // 高亮处理
    formatStr (item) {
      const reg = new RegExp(this.value, 'gi')
      return item.replace(reg, `<span style="color:red">${this.value}</span>`)
    },
    // 点击联想建议
    clickSuggestion (val) {
      this.$emit('search', val)
    }
  },
  beforeDestroy () {
    // this.loadSearchSuggestion = function () { }
    this.isShow = false
  }
}
</script>

<style scoped lang='less'>
</style>
